package com.tang.k.wechatmessage.application.NewsList.presenter;

import android.content.Intent;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;

import java.util.Date;

import com.tang.k.wechatmessage.application.NewsDetail.DetailActivity;
import com.tang.k.wechatmessage.application.NewsList.modle.INews;
import com.tang.k.wechatmessage.application.NewsList.modle.News;
import com.tang.k.wechatmessage.application.NewsList.modle.WeChat;
import com.tang.k.wechatmessage.application.NewsList.presenter.service.RetrofitWrapper;
import com.tang.k.wechatmessage.application.NewsList.presenter.service.WeChatservice;
import com.tang.k.wechatmessage.application.NewsList.view.ArticleActivity;
import com.tang.k.wechatmessage.application.NewsList.view.IArtivityView;
import com.tang.k.wechatmessage.application.R;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by tangk on 2016/9/12.
 */
public class ArticlePresenterImpl implements IArticlePresenter {
    private static final String TAG = "ArticlePresenterImpl";

    private DateFormat format = new SimpleDateFormat("yy-MM-dd HH:mm:ss");

    private static final int NotifyData = 1;
    private boolean isRefreshing = false;

    private IArtivityView view; //View的实例
    private Handler handler;

    public ArticlePresenterImpl(IArtivityView view) {
        this.view = view;
        this.handler = new Handler();
    }

    /**
     * 对应swipeRefreshLayout的onRefresh方法
     */
    @Override
    public void refresh() {

        Log.e(TAG, "refresh");
        //4秒无结果视为刷新失败
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (view.getSwipeState() == true) {
                    setRefreshState(false);
                    setRefreshFailure();
                }
            }
        }, 1000 * 4);
        //避免重复刷新
        if (isRefreshing) {
            return;
        }
        //获取数据
        getServerData();

    }

    /**
     * 对应于View的onResume;
     * 自动刷新
     */
    @Override
    public void onResume() {
        //设置SwipeRefreshLayout的状态为正在刷新

        setRefreshState(true);
        //获取数据
        getServerData();
    }

    /**
     * 从服务器端获取数据
     */
    @Override
    public void getServerData() {

        WeChatservice weChatservice = RetrofitWrapper.getInstance().create(WeChatservice.class);

        //Restful GET 请求
        Call<WeChat> call = weChatservice.getWeChatInfoList(1, 20, "json",
                "35ac74b213b1661e741efa66438c13d2");
        //加入去请求队列,监听两个回调
        call.enqueue(new Callback<WeChat>() {
            @Override
            public void onResponse(Call<WeChat> call, final Response<WeChat> response) {
                WeChat weChat = response.body();

                boolean isUsefulResponse = true;
                if (weChat == null) {
                    isUsefulResponse = false;
                } else if (weChat.getResult() == null) {
                    isUsefulResponse = false;

                } else if (weChat.getResult().getList() == null) {
                    isUsefulResponse = false;
                }
                if (!isUsefulResponse) {
                    setRefreshFailure();
                    setRefreshState(false);
                }
                List<News> listFromAPI = weChat.getResult().getList();
                List<INews> list = new ArrayList<>();

                for (News news : listFromAPI) {
                    News mNews = new News();
                    mNews.setFirstImg(news.getFirstImg());
                    mNews.setId(news.getId());
                    mNews.setSource(news.getSource());
                    mNews.setTitle(news.getTitle());
                    mNews.setUrl(news.getUrl());
                    //下面这几个数据是写死的,为了填充布局
                    mNews.setTimestamp(format.format(new Date(System.currentTimeMillis())));
                    mNews.setReadNum(100);
                    mNews.setCommentNum(50);
                    mNews.setFavoriteNum(10);
                    list.add(mNews);
                    //这个位置没有进行持久化操作 ，可以加上
                }
                if (list != null && list.size() > 0) {
                    //将数据传递给View的回调方法，用于更新数据;通知View的RecyclerView更新视图
                    view.onReceivedData(list);
                }

                //设置swipeRefreshLayout状态为未刷新
                setRefreshState(false);
            }

            //设置刷新状态为未刷新，显示刷新失败通知
            @Override
            public void onFailure(Call<WeChat> call, Throwable t) {
                setRefreshFailure();
                setRefreshState(false);
            }
        });
    }

    /**
     * 通知View改变SwipeRefreshLayout的刷新状态
     */
    @Override
    public void setRefreshState(boolean isRefreshing) {
        view.onRefreshStateChanged(isRefreshing);

    }

    /**
     * 当View onDestroy时触发，解除V和P的关联
     */
    @Override
    public void onDestroy() {
        view = null;
        handler.removeCallbacksAndMessages(null);
        handler = null;
    }

    /**
     * 刷新失败的回调
     */
    @Override
    public void setRefreshFailure() {
        view.onRefreshFailure();
    }

    /**
     * View中RecyclerView的Item点击事件回调；跳转到新Activity
     */
    @Override
    public void openDeatailWebView(String url) {
        if (url == null || url.equals("")) {
            return;
        }
        Intent intent = new Intent((ArticleActivity) view, DetailActivity.class);
        intent.putExtra("url", url);
        ((ArticleActivity) view).startActivity(intent);
    }

    /**
     * View中Back按钮按下的回调；
     * 连续按两下退出应用
     */
    private long lastTime = 0L;

    @Override
    public void handleBackPressed() {
        if (System.currentTimeMillis() - lastTime > 2000) {

            lastTime = System.currentTimeMillis();
            Snackbar.make(((ArticleActivity) view).findViewById(R.id.swipeRefreshLayout),
                    "再按一下退出应用", Snackbar.LENGTH_SHORT).setAction("取消", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    lastTime = 0L;
                }
            }).show();
        } else {
            ((ArticleActivity) view).finish();

        }

    }
}
